package com.dick.weixin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

import com.dick.weixin.util.logging.Logger;
import com.dick.weixin.util.logging.LoggerFactory;

public class CommonUtil {

	private static Logger log = LoggerFactory.getLogger(CommonUtil.class);

	/**
	 * 计算采用utf-8编码方式时字符串所占字节数
	 * 
	 * @param content
	 * @return
	 */
	public static int getByteSize(String content) {
		int size = 0;
		if (null != content) {
			try {
				// 汉字采用utf-8编码时占3个字节
				size = content.getBytes("utf-8").length;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return size;
	}

	/**
	 * 将微信消息中的CreateTime转换成标准格式的时间（yyyy-MM-dd HH:mm:ss）
	 * 
	 * @param createTime
	 *            消息创建时间
	 * @return
	 */
	public static String formatTime(String createTime) {
		// 将微信传入的CreateTime转换成long类型，再乘以1000
		long msgCreateTime = Long.parseLong(createTime) * 1000L;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date(msgCreateTime));
	}

	/**
	 * 按照偏移量取得相应的星期几
	 * 
	 * @param count
	 *            (最小可传 -7 )
	 * @return
	 */
	public static String getWeek(Integer count) {
		int dayInWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		dayInWeek += count;
		String week = "";
		if (dayInWeek <= 0) {
			dayInWeek += 7;
		}
		if (dayInWeek > 7) {
			dayInWeek = dayInWeek % 7;
			if (dayInWeek == 0) {
				dayInWeek = 7;
			}
		}
		System.out.println(dayInWeek);
		if (dayInWeek == 1)
			week = "星期天";
		else if (dayInWeek == 2)
			week = "星期一";
		else if (dayInWeek == 3)
			week = "星期二";
		else if (dayInWeek == 4)
			week = "星期三";
		else if (dayInWeek == 5)
			week = "星期四";
		else if (dayInWeek == 6)
			week = "星期五";
		else if (dayInWeek == 7)
			week = "星期六";
		return week;
	}

	/**
	 * 计算两个经纬度之间的距离（m）
	 * 
	 * @return
	 */
	public static String getDistanceByXY(Float lat_a, Float lng_a, Float lat_b,
			Float lng_b) {
		Double radLat1 = rad(lat_a);
		Double radLat2 = rad(lat_b);
		Double a = radLat1 - radLat2;
		Double b = rad(lng_a) - rad(lng_b);
		Double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * Constant.EARTH_RADIUS * 1000;
		Double s1 = s % 1;
		if (s1.compareTo(0.5) >= 0) {
			s = s - s1 + 1;
		} else {
			s = s - s1;
		}
		String str = s.toString();
		return str.substring(0, str.length() - 2);
	}

	public static Double rad(Float lat) {
		return lat * Math.PI / 180.0;
	}

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST)
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			log.error("Weixin server connection timed out.");
		} catch (Exception e) {
			log.error("https request error:{}", e);
		}
		return jsonObject;
	}
}
